package com.weipeep.demo;

import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfOutline;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.navigation.PdfExplicitDestination;
import com.itextpdf.kernel.utils.PdfMerger;

import java.io.File;
import java.io.IOException;

public class MergeClassServiceImpl {
    public static final String DEST
            = "merge_with_outlines.pdf";
    public static final String SRC1
            = "hello.pdf";
    public static final String SRC2
            = "links1.pdf";
    public static final String SRC3
            = "links2.pdf";

    public static void main(String[] args) throws IOException {
        new MergeClassServiceImpl().manipulatePdf(DEST);
    }

    public void manipulatePdf(String destFolder) throws IOException {
        PdfDocument pdfDoc = new PdfDocument(new PdfWriter(DEST));
        PdfMerger merger = new PdfMerger(pdfDoc);
        PdfOutline rootOutline = pdfDoc.getOutlines(false);

        int page = 1;

        PdfDocument srcDoc1 = new PdfDocument(new PdfReader(SRC1));
        merger.merge(srcDoc1, 1, srcDoc1.getNumberOfPages());

        PdfDocument srcDoc2 = new PdfDocument(new PdfReader(SRC2));
        PdfDocument srcDoc3 = new PdfDocument(new PdfReader(SRC3));
        merger.setCloseSourceDocuments(true)
                .merge(srcDoc2, 1, srcDoc2.getNumberOfPages())
                .merge(srcDoc3, 1, srcDoc3.getNumberOfPages());

        PdfOutline helloWorld = rootOutline.addOutline("Hello World");
        helloWorld.addDestination(PdfExplicitDestination.createFit(pdfDoc.getPage(page)));
        page += srcDoc1.getNumberOfPages();

        PdfOutline link1 = helloWorld.addOutline("link1");
        link1.addDestination(PdfExplicitDestination.createFit(pdfDoc.getPage(page)));
        page += srcDoc1.getNumberOfPages();

        PdfOutline link2 = rootOutline.addOutline("Link2");
        link2.addDestination(PdfExplicitDestination.createFit(pdfDoc.getPage(page)));

        srcDoc1.close();
        pdfDoc.close();
    }
}
